package cn.lm.demo01;


import java.sql.*;
import java.text.MessageFormat;

public class Main {
    // 数据库连接参数
    private static final String connectionStr = "jdbc:mysql://127.0.0.1:3306/limindb" +
            "?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=" +
            "Asia/Shanghai&allowPublicKeyRetrieval=true";

    // 数据库登录用户名
    private static final String username = "root";

    // 数据库登录密码
    private static final String password = "root";

    public static void main(String[] args) throws ClassNotFoundException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 1. 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取数据库连接
            conn = DriverManager.getConnection(connectionStr,username,password);

            // 3. 创建Statement对象
            stmt = conn.createStatement();

            // 4. 执行SQL查询
            String sql = "Select id,name,author,price From t_book";
            rs = stmt.executeQuery(sql);

            // 5. 处理结果集
            while(rs.next()){
                String info = MessageFormat.format("图书Id:{0},图书名称:{1},图书作者:{2},图书价格:{3}",
                        rs.getInt("id"),rs.getString("name"),
                        rs.getString("author"),rs.getDouble("price"));
                System.out.println(info);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动加载失败!");
            e.printStackTrace();
        } catch(SQLException e) {
            System.out.println("数据库操作异常!");
            e.printStackTrace();
        }finally{
            // 6. 关闭资源
            try {
                if(rs!=null) rs.close();
                if(stmt!=null) stmt.close();
                if(conn!=null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}